package org.example;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.*;
import java.awt.image.BufferedImage;

public class JAVACV {
    // 创建全局转换器实例以提高性能
    private static final Java2DFrameConverter converter = new Java2DFrameConverter();

    public static BufferedImage frameToBufferedImage(Frame frame) {
        // 确保frame不为null且有图像数据
        if (frame == null || frame.image == null) {
            return null;
        }

        try {
            return converter.convert(frame);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final int TARGET_FPS = 60;
    private static final String OUTPUT_FILENAME = "screen_capture.mp4";

    public static void main(String[] args) throws FrameGrabber.Exception {
        // 设置捕获区域（全屏）
        int x = 600, y = 400;
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        int width = 83;
        int height = 123;
        Rectangle screenRect2 = new Rectangle(600, 400, 83, 123); // 你可以根据需要设置屏幕尺寸
        FFmpegFrameGrabber.tryLoad();

        // 使用 gdigrab 设备创建抓取器
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("desktop");
        grabber.setFormat("gdigrab");
        grabber.setImageWidth(width);
        grabber.setImageHeight(height);
        grabber.setFrameRate(TARGET_FPS);
        grabber.setOption("offset_x", String.valueOf(x));
        grabber.setOption("offset_y", String.valueOf(y));

        try {
            grabber.start();
            Frame capturedFrame;
            while ((capturedFrame = grabber.grab()) != null) {
                BufferedImage bufferedImage = frameToBufferedImage(capturedFrame);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                grabber.stop();
                grabber.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
